package com.coderly.onlinegallerysharingplatform.event.subscriber;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.coderly.onlinegallerysharingplatform.event.ViewPictureEvent;
import com.coderly.onlinegallerysharingplatform.model.dao.entity.PictureDO;
import com.coderly.onlinegallerysharingplatform.model.dao.mapper.PictureMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class ViewPictureSubscriber implements ApplicationListener<ViewPictureEvent> {

    @Resource
    private PictureMapper pictureMapper;

    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(ViewPictureEvent event) {
        // 在这里处理收到的事件，可以是任何逻辑操作
        Long pictureId = event.getPictureId();

        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        log.info("==> threadName: {}", threadName);
        log.info("==> 浏览图片事件消费成功，articleId: {}", pictureId);

        UpdateWrapper<PictureDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("view_count = view_count + 1") // 直接使用 SQL 语句自增
                .eq("id", pictureId); // 条件：根据 id 更新
        pictureMapper.update(null, updateWrapper);
    }
}
